package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.dubbo.api.RecommendVideoApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.dubbo.api.VideoApi;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongoDb.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Pan Rundong
 * @Date 2023-03-07 13:06
 * @Desc
 */
@Service
public class SmallVideosService {
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @DubboReference
    private RecommendVideoApi recommendVideoApi;
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    /**
     * 发布小视频
     *
     * @param videoThumbnail
     * @param videoFile
     * @return void
     * @Author Pan Rundong
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        // 0.判断文件及图片是否为空
        if (videoThumbnail.isEmpty() || videoFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        // 1.获取用户Id
        Long userId = UserThreadLocal.getUserId();

        // 2.上传FastDFS
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        // 3.上传阿里云OSS
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        // 4.调用Api存入MongoDb
        Video video = new Video();
        video.setUserId(userId);
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");

        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

    }

    /**
     * 获取视频列表
     *
     * @param page
     * @param pagesize
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //1、查询redis数据
        Long userId = UserThreadLocal.getUserId();
        String redisKey = Constants.VIDEOS_RECOMMEND + userId;
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if(!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if( (page -1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e->Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length,pagesize);
        }

        //4、如果redis数据不存在，分页查询视频数据
        if(list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }

        // 5.获取视频对应用户Id，封装到list中，调用Api获取对应用户信息
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(ids, null);

        // 6.封装Vo
        List<VideoVo> voList = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            if (userInfo == null) {
                VideoVo vo = VideoVo.init(userInfo, video);
                voList.add(vo);
            }
        }

        // 7.返回
        return new PageResult(page, pagesize, 0, voList);
    }
}
